package com.example.teaculture.activity;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.teaculture.DB.DBOpenHelper;
import com.example.teaculture.DB.HistoryDao;
import com.example.teaculture.R;
import com.example.teaculture.model.Favor;
import com.yechaoa.yutils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HistoryActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private DBOpenHelper helper;
    private SQLiteDatabase sd;
    private ArrayList<Favor> historylist;
    private List<Map<String, String>> data = new ArrayList<Map<String, String>>();
    private ListView lv;
    private ImageView iv_clear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        lv = findViewById(R.id.lv_list);
        iv_clear = findViewById(R.id.iv_clear);
        //创建或打开数据库
        helper = new DBOpenHelper(HistoryActivity.this);
        sd = helper.getReadableDatabase();
        historylist = new ArrayList<>();
        //扫描数据库,将数据库信息放入studentlist

        HistoryDao historyDao = new HistoryDao(HistoryActivity.this);
        List<Favor> list = historyDao.findSelected();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Log.i("TAG:", "    " + list.get(i).getTitle());
                Map<String, String> map = new HashMap<String, String>();
                map.put("标题", list.get(i).getTitle());
                data.add(map);
            }
        }
        lv.setAdapter(new SimpleAdapter(this, data, android.R.layout.simple_list_item_1,
                new String[]{"标题"},            //每行显示一个姓名
                new int[]{android.R.id.text1}   //名字在text1上显示
        ));
        lv.setOnItemClickListener((adapterView, view, i, l) -> {
            Favor favor = historyDao.selectByDocId(list.get(i).getDocid());
            Intent intent = new Intent(this, FavorDetailActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.putExtra("url", favor.getUrl());
            intent.putExtra("title", favor.getTitle());
            startActivity(intent);
        });

        iv_clear.setOnClickListener(v->{
            historyDao.del();
            ToastUtil.show("清空成功");
            this.finish();
        });
    }

    public void hback(View view) {
        this.finish();
    }
}

